import { createStore, createLogger } from 'vuex'
import axios from 'axios'

// ts 类型
type PayMethodType = "支付宝" | "微信"

export type StateType = "待付款" | "待发货" | "已发货" | "已完成" | "已关闭" | "全部订单"

export interface ListItemState {
  "id": string,
  "createTime": string,
  "tel": number,
  "price": number,
  "payMethod": PayMethodType
  "state": StateType
}

interface UserState {
  isLogin: boolean
  token: string
  avator?: string
  username: string
}

export interface RootState {
  list: ListItemState[],
  user: UserState
}

export default createStore<RootState>({
  state: {
    list: [],
    user: {
      isLogin: false,
      token: localStorage.getItem('token') || '',
      username: ''
    }
  },
  mutations: {
    SET_LIST(state, payload: ListItemState[]) {
      state.list = payload
    },
    SET_USER(state, payload) {
      state.user = Object.assign(state.user, payload)
    }
  },
  actions: {
    async fetchOrderList(context, params) {
      const resp = await axios.get('/api/order/list', { params });
      const { data } = resp.data;
      context.commit('SET_LIST', data)
    },
    deleteOrderList(context, data) {
      return new Promise((resolve, reject) => {
        axios.post('/api/order/list/delete', data).then(resp => {
          const { code, message } = resp.data
          if (code === 200) {
            resolve(message)
          }
          reject(null)
        })
      })
    },
    login(context, data) {
      return new Promise((resolve, reject) => {
        axios.post('/api/user/login', data).then(resp => {
          const { code, data, message } = resp.data
          if (code === 200) {
            context.commit('SET_USER', { 
                token: data.token, 
                isLogin: true,
                username: data.username
            })
            resolve(resp.data)
          } else {
            reject(message)
          }
        })
      })
    }
  },
  modules: {
  },
  plugins: [createLogger()]
})
